var rootPath = getRootPath();

$(function() {
	$.ajax({
		url: rootPath + '/resource/queryResourcesByDr?dr=1',
        type: 'GET',
        success: function (data) {
        	var length = data.returnObject.length;
        	var dt = "";
        	for(var i = 0;i < length;i++) {
        		dt += "<dt style='width:150px'><label class=''>";
        		dt += "<input type='checkbox' value='" + data.returnObject[i].resId + "' name='resIds'>" 
        		dt += data.returnObject[i].resName + " </label></dt>";
        	}
        	$("#resources").append(dt);
        	
        	
    		$("#roleAddForm").validate({
    			rules:{
    				rleName:{
    					required:true,
    					maxlength:50,
    					remote : {
    						type : "GET",
    						url : rootPath + "/role/checkRleName",
    						data : {
    							rigName : function() {
    								return $("#rleName").val();
    							}
    						},
    						dataFilter : function(data,type) {
    							if(data == "true") {
    								return true;
    							} else {
    								return false;
    							}
    						}
    					}
    				}
    			},
    			messages: {
    				rleName:{
    					remote : "角色名称已存在"
    				}
    			},
    			onkeyup:false,
    			focusCleanup:true,
    			success:"valid",
    			submitHandler:function(form){
    				var jsonObject = JSON.parse(JSON.stringify($('#roleAddForm').serializeJson()));
    				var json;
    				if(jsonObject.resIds == null) {
    					jsonObject.resIds = [];
    					json = JSON.stringify(jsonObject);
    				} else {
    					json = JSON.stringify($('#roleAddForm').serializeJson());
    				}
    				$.ajax({
    					url: rootPath + '/role/saveRoleRes',
    			        type: 'POST',
    			        data : JSON.stringify($('#roleAddForm').serializeJson()),
    		            contentType: 'application/json;charset=UTF-8', 
    			        success: function (data) {
    						if(data.returnCode == "0000") {						
    							layer.msg('成功增加权限!',{icon:1,time:1000},function() {						
    								parent.window.location.href = rootPath + '/rolePage';
    								var index = parent.layer.getFrameIndex(window.name);
    								parent.layer.close(index);
    							});
    						} else {
    							layer.alert(data.returnMessage);
    						}
    			        },
    			        error: function (jqXHR, textStatus, errorThrown) {
    			        	layer.alert("新增权限失败:(");
    			        }
    			    });
    			}
    		});
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	layer.alert("获取资源失败:(");
        }
    });
});